package cn.easyplatform.studio.web.editors.project;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.exportAll.GetDicCmd;
import cn.easyplatform.studio.cmd.exportAll.PagingDicCmd;
import cn.easyplatform.studio.cmd.exportAll.RootDicCmd;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.DicVo;
import cn.easyplatform.studio.vos.QueryDicVo;
import cn.easyplatform.studio.web.editors.ComponentCallback;
import cn.easyplatform.studio.web.editors.version.AllExportEditor;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DictExportEditor extends AllExportEditor {
    protected enum CheckItem {
        SelectedAllItem, UnSelectedAllItem, SelectedPageItem, UnSelectedPageItem
    }
    protected Paging showPaging;
    protected CheckItem checkItem;
    protected int checkPage = -1;

    private DicVo searchVo;
    private List<DicVo> allList;
    private QueryDicVo queryDicVo;

    public DictExportEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    protected void dispatch(Event evt) {
        if (evt.getTarget() == showPaging) {// 分页
            PagingEvent pe = (PagingEvent) evt;
            int pageNo = pe.getActivePage() + 1;
            queryDicVo = StudioApp.execute(showPaging,
                    new PagingDicCmd(searchVo, showPaging.getPageSize(), pageNo, allList));
            redrawList(queryDicVo.getLinkVoList());
        } else if (evt.getTarget() instanceof Treeitem) {
            if (Events.ON_OPEN.equals(evt.getName())) {
                Treeitem item = (Treeitem) evt.getTarget();
                DicVo vo = item.getValue();
                queryDicVo = StudioApp.execute(item, new RootDicCmd(queryDicVo, vo, allList));
                redrawList(queryDicVo.getLinkVoList());
            }
        } else if (evt.getName().equals(Events.ON_CLICK)) {
            Component comp = evt.getTarget();
            if (comp.getId().equals("dicExport_button_query")) {
                searchVo = new DicVo();
                searchVo.setDicCode(id.getValue());
                searchVo.setDesc1(desp.getValue());
                queryDicVo = StudioApp.execute(showPaging,
                        new PagingDicCmd(searchVo, showPaging.getPageSize(), 1, allList));
                if (Double.valueOf(queryDicVo.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
                    showPaging.setVisible(false);
                else {
                    showPaging.setVisible(true);
                    showPaging.setActivePage(0);
                    showPaging.setTotalSize(queryDicVo.getTotalSize());
                }
                allListCheck.setChecked(false);
                pageListCheck.setChecked(false);
                revListCheck.setChecked(false);
                checkPage = -1;
                redrawList(queryDicVo.getLinkVoList());
            } else if (comp.getId().equals("dicExport_image_chooseAllBtn")) {
                select(false);
            } else if (comp.getId().equals("dicExport_image_chooseBtn")) {
                select(true);
            } else if (comp.getId().equals("dicExport_image_removeBtn")) {
                unselect(true);
            } else if (comp.getId().equals("dicExport_image_removeAllBtn")) {
                unselect(false);
            } else if (comp.getId().equals("dicExport_toolbarbutton_export")) {
                export(comp);
            } else if (comp instanceof Treerow) {
                comp = (Treerow) comp;
                Treeitem currentItem = (Treeitem) comp.getParent();
                if (currentItem.isSelected() == true) {
                    while (currentItem.getParentItem() != null) {
                        currentItem.getParentItem().setSelected(true);
                        currentItem = currentItem.getParentItem();
                    }
                }
            }
        } else if (evt.getName().equals(Events.ON_CHECK)) {
            Checkbox r = (Checkbox) evt.getTarget();
            doCheck(r);
        } else if (evt.getName().equals(Events.ON_DOUBLE_CLICK)) {
            Treerow row = (Treerow) evt.getTarget();
            Treeitem treeitem = (Treeitem) row.getParent();
            DicVo dicVo = treeitem.getValue();
            AbstractView.createDicDetailView(new ComponentCallback(this.id, Labels.getLabel("dic.detail.title")),
                    dicVo.getDicDetailVoList()).doOverlapped();
        }
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.repo.export.dictionary"), "~./images/dictionary.png",
                "~./include/editor/project/dictExport.zul");
        this.id = (Textbox)is.getFellow("dicExport_textbox_id");
        this.desp = (Textbox)is.getFellow("dicExport_textbox_desp");
        this.sources = (Tree)is.getFellow("dicExport_tree_sources");
        this.targets = (Listbox)is.getFellow("dicExport_listbox_targets");
        this.comment = (Textbox) is.getFellow("dicExport_textbox_comment");
        showPaging = (Paging) is.getFellow("dicExport_paging_showPaging");
        Button searchBtn = (Button)is.getFellow("dicExport_button_query");
        searchBtn.addEventListener(Events.ON_CLICK, this);
        allListCheck = (Checkbox)is.getFellow("dicExport_checkbox_checkAll");
        allListCheck.addEventListener(Events.ON_CHECK, this);
        pageListCheck = (Checkbox)is.getFellow("dicExport_checkbox_checkPage");
        pageListCheck.addEventListener(Events.ON_CHECK, this);
        revListCheck = (Checkbox)is.getFellow("dicExport_checkbox_checkRev");
        revListCheck.addEventListener(Events.ON_CHECK, this);
        is.getFellow("dicExport_image_chooseAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("dicExport_image_chooseBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("dicExport_image_removeBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("dicExport_image_removeAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("dicExport_toolbarbutton_export").addEventListener(Events.ON_CLICK, this);
        redraw();
    }

    private void redraw() {
        allList = StudioApp.execute(new GetDicCmd(null, null));
        queryDicVo = StudioApp.execute(new PagingDicCmd(null, showPaging.getPageSize(), 1, allList));
        if (Double.valueOf(queryDicVo.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
            showPaging.setVisible(false);
        else {
            showPaging.setVisible(true);
            showPaging.setTotalSize(queryDicVo.getTotalSize());
            showPaging.addEventListener(ZulEvents.ON_PAGING, this);
        }
        redrawList(queryDicVo.getLinkVoList());
    }

    private void redrawList(List<DicVo> list) {
        sources.clear();
        Treechildren treechildren = null;
        if (null == sources.getTreechildren()) {
            treechildren = new Treechildren();
            sources.appendChild(treechildren);
        }
        else {
            treechildren = sources.getTreechildren();
        }
        allTreechildren(treechildren, list);
    }
    private Treechildren allTreechildren(Treechildren children, List<DicVo> list) {
        for (DicVo vo : list) {
            final Treeitem item = new Treeitem();
            item.setValue(vo);
            Treerow row = new Treerow();
            row.setHeight("32px");
            row.appendChild(new Treecell(vo.getDicCode()));
            row.appendChild(new Treecell(vo.getDesc1()));
            row.appendChild(new Treecell(vo.getUpCode()));
            row.appendChild(new Treecell(vo.getCreateDate() != null ? vo.getCreateDate().toString():""));
            row.appendChild(new Treecell(vo.getCreateUser()));
            row.addEventListener(Events.ON_DOUBLE_CLICK, this);
            row.addEventListener(Events.ON_CLICK, this);
            item.appendChild(row);

            boolean isAddRoot = false;
            if (null != vo.getChildrenList() && vo.getChildrenList().size() != 0)
            {
                Treechildren ch = allTreechildren(new Treechildren(), vo.getChildrenList());
                item.appendChild(ch);
            } else {
                if (Strings.isBlank(vo.getUpCode()) || vo.getUpCode().equals(" "))
                    isAddRoot = true;
            }

            if (isAddRoot == true) {
                Treechildren childrenTree = new Treechildren();
                item.appendChild(childrenTree);
                item.setOpen(false);
                item.addEventListener(Events.ON_OPEN, this);
            }
            if (checkItem == CheckItem.SelectedAllItem)
                item.setSelected(true);
            else if ((checkItem == CheckItem.UnSelectedAllItem))
                item.setSelected(false);
            else if (checkPage == showPaging.getActivePage() + 1 && checkItem == CheckItem.SelectedPageItem)
                item.setSelected(true);
            else
                item.setSelected(false);
            children.appendChild(item);
        }
        return children;
    }

    private void select(boolean selectFlag) {
        for (Treeitem sel : sources.getItems()) {
            if (selectFlag && !sel.isSelected())
                continue;
            if (sel.getValue() != null) {
                boolean exists = false;
                DicVo s = sel.getValue();
                for (Listitem li : targets.getItems()) {
                    DicVo t = li.getValue();
                    if (s.getDicCode().equals(t.getDicCode())) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    Listitem li = new Listitem();
                    li.appendChild(new Listcell(s.getDicCode()));
                    li.appendChild(new Listcell(s.getDesc1()));
                    li.appendChild(new Listcell(s.getUpCode()));
                    li.appendChild(new Listcell(s.getCreateDate().toString()));
                    li.appendChild(new Listcell(s.getCreateUser()));
                    li.setValue(s);
                    targets.appendChild(li);
                }
            }
        }
    }

    private void unselect(boolean selectedFlag) {
        if (selectedFlag) {
            if (targets.getSelectedCount() > 0) {
                List<Listitem> items = new ArrayList<Listitem>();
                for (Listitem li : targets.getSelectedItems())
                    items.add(li);
                for (Listitem li : items)
                    li.detach();
            }
        } else
            targets.getItems().clear();
    }

    protected void doCheck(Checkbox cbx) {
        if (cbx.getValue().equals("1") || cbx.getValue().equals("3")) {
            Iterator<Component> itr = sources.queryAll("treeitem").iterator();
            while (itr.hasNext()) {
                Treeitem ti = (Treeitem) itr.next();
                if (ti.getValue() != null) {

                    if (cbx.getValue().equals("1")) {
                        ti.setSelected(cbx.isChecked());
                        if (cbx.isChecked())
                            checkItem = CheckItem.SelectedAllItem;
                        else
                            checkItem = checkItem.UnSelectedAllItem;
                    }
                    else {
                        ti.setSelected(!ti.isSelected());
                        if (ti.isSelected())
                            checkItem = CheckItem.SelectedAllItem;
                        else
                            checkItem = checkItem.UnSelectedAllItem;
                    }
                }
            }
        } else {
            int pos = showPaging.getActivePage() * showPaging.getPageSize();
            int to = (showPaging.getActivePage() + 1) * showPaging.getPageSize();
            if (cbx.isChecked())
                checkItem = CheckItem.SelectedPageItem;
            else
                checkItem = checkItem.UnSelectedPageItem;
            checkPage = showPaging.getActivePage() + 1;
            List<Treeitem> data = new ArrayList<Treeitem>(sources.getItems());
            for (; pos < to; pos++) {
                if (data.size()>pos) {
                    Treeitem ti = data.get(pos);
                    ti.setSelected(cbx.isChecked());
                }
            }
        }
    }

    //导出
    protected void export(Component btn) {
        if (targets.getItems().isEmpty()) {
            WebUtils.showError(Labels.getLabel("editor.export.empty"));
            return;
        }
        if (Strings.isBlank(comment.getValue())) {
            WebUtils.notEmpty(Labels.getLabel("editor.export.comment"));
            return;
        }
        Clients.clearWrongValue(btn);
        //打包保存
        List<DicVo> dicVos = new ArrayList<DicVo>();
        for (Listitem li : targets.getItems()) {
            DicVo e = li.getValue();
            dicVos.add((DicVo)e.clone());
        }
        StudioUtil.exportDic(dicVos, comment.getValue());
    }
}
